<template>
	<div class="app-container">
		<el-form :inline="true" :model="dataForm" @submit.native.prevent @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input placeholder="请输入角色名搜索" v-model="dataForm.roleName" :clearable="true" size="mini">
          <template slot="prepend">角色名</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="pan-btn primary-btn" size="mini" @click="searchData()" icon="el-icon-search">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button v-if="isAuth('sys:role:save')" @click="addModule()" type="success" class="pan-btn success-btn" size="mini" icon="el-icon-upload">新增</el-button>
      </el-form-item>

      <el-form-item>
        <el-button v-if="isAuth('sys:role:delete')" @click="deleteData()" type="danger" class="pan-btn danger-btn" size="mini" icon="el-icon-delete">删除</el-button>
      </el-form-item>
    </el-form>

		<el-table
			:data="dataList"
			v-loading="dataListLoading"
			border
      fit
      highlight-current-row
			@selection-change="selectionChange"
	    style="width: 100%">
    <el-table-column
      type="selection"
      header-align="center"
      align="center"
      width="50">
    </el-table-column>
    <el-table-column
			prop="roleId"
			header-align="center"
			align="center"
			label="角色编号"
			width="200">
		</el-table-column>
		<el-table-column
			prop="roleName"
			header-align="center"
			align="center"
			label="角色名">
		</el-table-column>
		<el-table-column
        fixed="right"
        header-align="center"
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('sys:role:update') && scope.row.roleId != 1" type="text" size="small" @click="updateData(scope.row)">修改</el-button>
          <el-button v-if="isAuth('sys:role:delete') && scope.row.roleId != 1" type="text" size="small" @click="deleteData(scope.row.roleId)">删除</el-button>
          <el-button v-if="isAuth('sys:role:collocate')" type="text" size="small" @click="collocate(scope.row.roleId)">配置</el-button>
        </template>
      </el-table-column>
		</el-table>
		<el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog
    	title="配置菜单"
    	:visible.sync="collocateVisible"
		  :before-close="collocateClose"
		  :close-on-click-modal="false"
		  width="30%">
      <el-card>
        <el-select v-model="checkedTypeIds" multiple v-if="allTypes.length" filterable placeholder="数据权限" size="mini" style="width: 100%;">
          <el-option
            v-for="item in allTypes"
            :key="item.checkTypeId"
            :label="item.checkTypeName"
            :value="item.checkTypeId">
          </el-option>
        </el-select>
      </el-card>
    	<el-tree
			  :data="menuList"
			  ref="tree"
			  show-checkbox
			  node-key="menuId"
			  :default-checked-keys="permIdList"
			  :props="menuProps">
			</el-tree>
			<span slot="footer" class="dialog-footer" v-if="noAdmin">
		    <el-button @click="collocateClose">取 消</el-button>
		    <el-button type="primary" class="pan-btn primary-btn" @click="collocateSubmit">确 定</el-button>
	  	</span>
    </el-dialog>
    <add-or-update-module
    	v-if="addModuleVisible"
    	@close="addModule"
    	@refreshData="getDataList"
    	:childDataForm="childDataForm"
    	></add-or-update-module>
	</div>
</template>

<script>
	import CommonMethod from '@/views/mixin/common'
	import { CODE_OK } from '@/common/js/config'
	import { getRoleList,updateRolecollocate,deleteRole,getTypeIdListByRoleId } from "@/api/role"
	import { getAllMenuList,getPermIdListByRoleId } from "@/api/menu"
  import { getCheckTypes } from '@/api/check'
	import AddOrUpdateModule from './role-addorupdatemodule'
	export default {
    name: 'juese',
		mixins: [CommonMethod],
		components: {
			AddOrUpdateModule
		},
		data() {
    	return {
	      dataForm: {},
	      dataList: [],
	      pageIndex: 1,
	      pageSize: 10,
	      totalPage: 0,
	      dataListLoading: false,
	      selectionList: [],
	      menuList: [],
	      menuAllList: [],
        allTypes: [],
        checkedTypeIds: [],
	      collocateVisible: false,
	      menuProps: {
          children: 'childList',
          label: 'menuName'
       	},
       	permIdList: [],
       	noAdmin: true,
       	checkRoleId: "",
       	addModuleVisible: false,
       	childDataForm: ""
	    }
  	},
  	mounted() {
      this.getInfo()
  		if (this.isAuth('sys:role:list')) {
  			this.getDataList()
  		}
  	},
  	methods: {
      getInfo() {
        getAllMenuList().then(res => {
        	if (res.code === CODE_OK) {
        		this.menuList = res.menuList
        		this.menuAllList = res.menuAllList
        	}else{
        		this.$message.error(res.msg)
        	}
        }).catch()
        getCheckTypes().then(res => {
          if (res.code === CODE_OK) {
          	this.allTypes = res.list
          }else{
          	this.$message.error(res.msg)
          }
        }).catch()
      },
  		deleteData(id) {
				if (this.selectionList.length == 0 && id == undefined) {
					this.$message.error('请选择至少一个角色')
					return
				}
				let ids = id ? [id] : this.selectionList.map(item => {
					return item.roleId
				})
				let msg = id ? '此操作将永久删除此角色, 是否继续?' : '此操作将永久删除选中的角色, 是否继续?'
				this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
       	}).then(() => {
       		deleteRole(ids).then(res => {
       			if (res.code === CODE_OK) {
       				this.$message({
		            type: 'success',
		            message: '删除成功!'
		          })
       				this.getDataList()
       			}else{
       				this.$message.error(res.msg)
       			}
       		})

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
			},
  		updateData(row) {
				this.childDataForm = row
				this.addModuleVisible = !this.addModuleVisible
			},
  		addModule() {
  			this.childDataForm = ""
  			this.addModuleVisible = !this.addModuleVisible
  		},
  		getCheckedIds() {
  			let checkedMenus = this.$refs.tree.getCheckedNodes()
  			let checkedIds = []
  			for (let i=0,j=checkedMenus.length; i<j; i++) {
  				let menu = checkedMenus[i]
  				checkedIds.push(menu.menuId)
  				if (menu.parentId != 0 && checkedIds.indexOf(menu.parentId) == -1) {
  					checkedIds.push(menu.parentId)
  					for (let k=0,l=this.menuAllList.length; k<l; k++) {
  						if (menu.parentId == this.menuAllList[k].menuId && checkedIds.indexOf(this.menuAllList[k].parentId) == -1 && this.menuAllList[k].parentId != 0) {
  							checkedIds.push(this.menuAllList[k].parentId)
  						}
  					}
  				}
  			}
  			return checkedIds
  		},
  		collocateSubmit() {
  			let ids = this.getCheckedIds()
  			if (ids.length == 0) {
  				this.$message.error("请配置菜单")
  				return
  			}
  			const data = {
  				ids,
  				roleId: this.checkRoleId,
          typeIds: this.checkedTypeIds
  			}
  			updateRolecollocate(data).then(res => {
  				if (res.code === CODE_OK) {
  					this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: this.collocateClose()
          	})
  				}else{
  					this.$message.error(res.msg)
  				}
  			}).catch()
  		},
  		collocateClose() {
  			this.collocateVisible = false
  			this.$refs.tree.setCheckedKeys([])
  		},
  		collocate(id) {
        this.permIdList = []
        this.checkedTypeIds = []
  			this.checkRoleId = id
  			this.noAdmin = true
  			this.collocateVisible = true
  			//超管所有权限并且去掉提交按钮
  			if (this.checkRoleId == 1) {
  				this.noAdmin = false
  				this.permIdList = [1,2,3,4,5]
          this.checkedTypeIds = this.allTypes.map(t => {
            return t.checkTypeId
          })
  				return
  			}
  			getPermIdListByRoleId(this.checkRoleId).then(res => {
  				if (res.code === CODE_OK) {
  					this.permIdList = res.permIdList
  				}else{
  					this.$message.error(res.msg)
  				}
  			}).catch()
        getTypeIdListByRoleId(this.checkRoleId).then(res => {
          if (res.code === CODE_OK) {
          	this.checkedTypeIds = res.list
          }else{
          	this.$message.error(res.msg)
          }
        }).catch()
  		},
  		searchData() {
  			this.pageIndex=1
  			this.getDataList()
  		},
			getDataList() {
	  		this.dataListLoading = true
	  		const params = {
	  			page: this.pageIndex,
	        limit: this.pageSize,
	  			roleName: this.dataForm.roleName || null
	  		}
	  		getRoleList(params).then(res => {
	  			if (res.code === CODE_OK) {
	  				this.dataList = res.page.list
	  				this.totalPage = res.page.totalCount
	  			}else{
	  				this.$message.error(res.msg)
	  			}
	  			this.dataListLoading = false
	  		}).catch()
			},
			selectionChange(obj) {
				this.selectionList = obj
			}
  	}
	}
</script>

<style scoped>
  >>> .el-form-item__content {
    line-height: normal;
  }
</style>
